package top.hmtools.wxmp.core.access_handle;

import java.util.Date;

import top.hmtools.wxmp.core.configuration.AppIdSecretBox;
import top.hmtools.wxmp.core.configuration.AppIdSecretPair;
import top.hmtools.wxmp.core.httpclient.HmHttpClientTools;
import top.hmtools.wxmp.core.model.AccessTokenBean;
import top.hmtools.wxmp.core.model.GetAccessTokenParam;

/**
 * 缺省的、简单的、基于单机本地内存存储方案的获取access token的中间件
 * @author HyboWork
 *
 */
public class DefaultAccessTokenHandle extends BaseAccessTokenHandle {
	
	private AccessTokenBean accessTokenBean;

	public DefaultAccessTokenHandle(AppIdSecretBox appIdSecretBoxParam) {
		super(appIdSecretBoxParam);
	}

	@Override
	public AccessTokenBean getAccessTokenBean() {
		//如果AT为空，则获取
		if(this.accessTokenBean == null){
			this.doGetAccessToken();
		}
		
		//如果临近过期，则获取
		long now = System.currentTimeMillis();
		long last = this.accessTokenBean.getLastModifyDatetime().getTime();
		if((now - last)>=(7000*1000)){
			this.doGetAccessToken();
		}
		return this.accessTokenBean;
	}
	
	private void doGetAccessToken(){
		AppIdSecretBox appIdSecretBox = this.getAppIdSecretBox();
		AppIdSecretPair appIdSecretPair = appIdSecretBox.getAppIdSecretPair();
		GetAccessTokenParam params = new GetAccessTokenParam(appIdSecretPair);
		this.accessTokenBean  = HmHttpClientTools.httpGetReqParamRespJson("https://api.weixin.qq.com/cgi-bin/token", params,AccessTokenBean.class);
		accessTokenBean.setLastModifyDatetime(new Date());
		accessTokenBean.setAppid(appIdSecretPair.getAppid());
		accessTokenBean.setSecret(appIdSecretPair.getAppsecret());
	}

}
